package com.wnxy.sddfp.sms.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.wnxy.sddfp.sms.config.SmsUtil;
import com.wnxy.sddfp.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private final SmsUtil smsUtil;
    @Autowired
    private final StringRedisTemplate stringRedisTemplate;

    public SmsServiceImpl(SmsUtil smsUtil, StringRedisTemplate redisTemplate) {
        this.smsUtil = smsUtil;
        this.stringRedisTemplate = redisTemplate;
    }

    /**
     * StringRedisTemplate  和  RedisTemplate 的区别?
     * 1、RedisTemplate 是  StringRedisTemplate 父类
     * 2、StringRedisTemplate 她的类型 extends RedisTemplate<String, String> 只能是String类型
     * 3、如果是 复杂的类型     RedisTemplate
     * 如果是  字符串的类型   StringRedisTemplate
     *
     * @return
     */

    @Override
    public Map<String, Object> sendCode(String phone) {
        // 生成验证码
        String code = RandomUtil.randomNumbers(4);

        // 验证码还没有过期，直接返回
        if (stringRedisTemplate.hasKey("SMS:" + phone)) {
            return null;
        }

        // 调用阿里云sms服务，发送验证码
        smsUtil.sendSms(phone, code);

        // 验证码存储到redis
        stringRedisTemplate.opsForValue().set("SMS:" + phone, code, Duration.ofMinutes(5));

        // 构建返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("phone", phone);

        return map;
    }
}
